var app = getApp();
var BaseUrl = app.globalData.BaseUrl;
var util = require('../utils/util.js');

// GET 请求头 X-FORM格式
let FROM = {'content-type': 'application/x-www-form-urlencoded',}
// POST 请求头 JSON格式
let JSON = {'content-type': 'application/json',}

const http = (options) => {
  var Token = wx.getStorageSync('token');
  if (Token) {
    let expires = new Date(new Date() * 1 + util.expiresIn)
    wx.setStorageSync('tokenExpire', expires) // 记录token有效期限(毫秒值) 有操作就更新token有效期

    FROM = {'content-type': 'application/x-www-form-urlencoded'};
    FROM['Authorization'] = 'Bearer ' + Token;
    JSON = {'content-type': 'application/json'};
    JSON['Authorization'] = 'Bearer ' + Token;
  } else {
    FROM = {'content-type': 'application/x-www-form-urlencoded'};
    JSON = {'content-type': 'application/json'};
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: BaseUrl + options.url,
      method: options.method || 'GET',
      header: options.method == 'GET' ? FROM : JSON,
      data: options.data,
      success(res) {
        if (res.statusCode == 200) {
          resolve(res.data)
        } else {
          reject();
        }
      }
    })
  })
}

module.exports = {
  http,
}